<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <canvas id="canvas" style="border: 1px solid red;"></canvas>

  <script>
    /*jshint browser:true*/
    var BLANK_IMG =
      ''
    var canvas = document.getElementById('canvas'),
      g = canvas.getContext('2d')
    var ws = new WebSocket('ws://' + location.host + "/minicap")
    ws.binaryType = 'blob'
    ws.onclose = function () {
      console.log('onclose', arguments)
      var warn = document.createElement("div")
      warn.innerText = "Websocket closed, Refresh to reload."
      warn.style.color = "red"
      warn.style.fontSize = "20px"
      document.body.appendChild(warn);
    }
    ws.onerror = function () {
      console.log('onerror', arguments)
    }
    ws.onmessage = function (message) {
      if (message.data instanceof Blob) {
        var blob = new Blob([message.data], {
          type: 'image/jpeg'
        })
        var URL = window.URL || window.webkitURL
        var img = new Image()
        img.onload = function () {
          console.log(img.width, img.height)
          canvas.width = img.width
          canvas.height = img.height
          g.drawImage(img, 0, 0)
          img.onload = null
          img.src = BLANK_IMG
          img = null
          u = null
          blob = null
        }
        var u = URL.createObjectURL(blob)
        img.src = u
      } else {
        console.log(message.data)
      }
    }
    ws.onopen = function () {
      console.log('onopen', arguments)
      ws.send('1920x1080/0')
    }
  </script>
</body>

</html>